package me.liuhui.mall.manager.service.security;

import me.liuhui.mall.manager.cache.RedisCache;
import me.liuhui.mall.manager.service.PermissionService;
import me.liuhui.mall.manager.service.RoleService;
import me.liuhui.mall.repository.mapper.AdminMapper;
import me.liuhui.mall.repository.model.Admin;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;

@Service
public class AdminUserDetailsService implements UserDetailsService {
    private static final String ADMIN_CACHE_KEY = "admin:permission:";
    @Resource
    private AdminMapper adminMapper;
    @Resource
    private PermissionService permissionService;
    @Resource
    private RoleService roleService;

    @Resource
    private RedisCache cache;
    @Override
    public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
        CurrentAdmin userDetails = cache.get(ADMIN_CACHE_KEY + username);
        if (userDetails == null) {
            Admin admin = adminMapper.selectByUsername(username);
            if (admin == null) {
                throw new UsernameNotFoundException("用户不存在");
            }
            userDetails = new CurrentAdmin(admin);
            userDetails.setPermissions(permissionService.currentPermissions(admin.getId()));
            userDetails.setRoles(roleService.currentRoles(admin.getId()));
            cache.set(ADMIN_CACHE_KEY + username, userDetails);
        }

        return userDetails;
    }
}
